﻿// http://blogs.msdn.com/b/mariya/archive/2007/01/05/forcing-httpwebrequest-to-use-kerberos-authentication.aspx


using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading;


//NTLM, Kerberos, Negotiate, Digest, or Basic

namespace HttpRequestSimple
{
    internal class Program
    {
        private static void Connect(string server, int port, string message)
        {
            try
            {
                var client = new TcpClient(server, port);
                var data = System.Text.Encoding.ASCII.GetBytes(message);
                var stream = client.GetStream();

                stream.Write(data, 0, data.Length);

                Console.WriteLine("Sent: {0}", message);

                data = new Byte[4096];

                var bytes = stream.Read(data, 0, data.Length);
                var responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                Console.WriteLine("Received: {0}", responseData);

                client.Close();
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException: {0}", e);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }

        }

        private static string path = "http://www.google.com.ar/";
        private static string host = "www.google.com.ar";
        private static string server = "127.0.0.1";      //"10.147.64.2"
        private static int port = 9090;      //8080

        static void Message0()
        {
            const string format = "GET {0} HTTP/1.1\r\nHost: {1}\r\nProxy-Connection: Keep-Alive\r\n\r\n";

            var message = String.Format(format, path, host);

            Connect(server, port, message);
        }


        static void Message1()
        {
            const string format = "GET {0} HTTP/1.1\r\nProxy-Authorization: Negotiate TlRMTVNTUAABAAAAl7II4gYABgAzAAAACwALACgAAAAGAbEdAAAAD1BST0ctRlJBLTMxQ0RTLUJB\r\nHost: {1}\r\n\r\n";

            var message = String.Format(format, path, host);

            Connect(server, port, message);
        }


                //GET http://www.google.com.ar/ HTTP/1.1
                //Proxy-Authorization: Negotiate TlRMTVNTUAADAAAAGAAYAKIAAAA+AT4BugAAAAwADABYAAAAK
                //AAoAGQAAAAWABYAjAAAABAAEAD4AQAAFYKI4gYBsR0AAAAPDd0Qrwbkk1FjWchkHYAtt0MARABTAC0AQ
                //gBBAEYAZQByAG4AYQBuAGQAbwAuAFAAZQBsAGwAaQBjAGMAaQBvAG4AaQBQAFIATwBHAC0ARgBSAEEAL
                //QAzADEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKGHutu9ufbfKkTbNboo8dwEBAAAAAAAAx6Se+fGBz
                //AFeIcYtY6izHgAAAAACAAwAQwBEAFMALQBCAEEAAQAQAFcAQQBSAEcAVABZADAAMQAEABgAYwBkAHMAL
                //QBiAGEALgBsAG8AYwBhAGwAAwAqAFcAQQBSAEcAVABZADAAMQAuAGMAZABzAC0AYgBhAC4AbABvAGMAY
                //QBsAAUAGABjAGQAcwAtAGIAYQAuAGwAbwBjAGEAbAAHAAgAx6Se+fGBzAEGAAQAAgAAAAgAMAAwAAAAA
                //AAAAAAAAAAAMAAAjVo+/JfTVt8xS0kQgrNqs4IwY07Dj4ONOyrqxSv4WngKABAAAAAAAAAAAAAAAAAAA
                //AAAAAkAHABIAFQAVABQAC8AMQAyADcALgAwAC4AMAAuADEAAAAAAAAAAAAAAAAAoqNnIQ1lYcnKkjaqo
                //1GuWw==
                //Host: www.google.com.ar



        //static void Main(string[] args)
        //{
        //    Message0();
        //    Message1();

        //    Console.WriteLine("\n Press Enter to continue...");
        //    Console.ReadLine();
        //}


        private static void DisplayRegisteredModules()
        {

            var registeredModules = AuthenticationManager.RegisteredModules;

            Console.WriteLine("\r\nThe following authentication modules are now registered with the system:");

            while (registeredModules.MoveNext())
            {
                Console.WriteLine("\r \n Module : {0}", registeredModules.Current);
                var currentAuthenticationModule = (IAuthenticationModule)registeredModules.Current;
                Console.WriteLine("\t  CanPreAuthenticate : {0}", currentAuthenticationModule.CanPreAuthenticate);
            }
        }


        private static void Main(string[] args)
        {
            //var pepe3 = System.Environment.UserDomainName;
            //var pepe2 = System.Net.Dns.GetHostName();
            //var ipProperties = IPGlobalProperties.GetIPGlobalProperties();
            //var pepe = string.Format("{0}.{1}", ipProperties.HostName, ipProperties.DomainName);


            const string nextUrl = "http://www.google.com.ar";

            var uri = new Uri(nextUrl);

            if (uri.Scheme == Uri.UriSchemeHttp)
            {
                var request = (HttpWebRequest)WebRequest.Create(uri);
                request.Method = WebRequestMethods.Http.Get;
                request.AllowAutoRedirect = true;
                request.Timeout = Timeout.Infinite;

                //var proxy2 = WebRequest.GetSystemWebProxy();
                //proxy2.Credentials = CredentialCache.DefaultCredentials;

                var proxy2 = new WebProxy("127.0.0.1", 9090);
                proxy2.Credentials = CredentialCache.DefaultCredentials;
                request.Proxy = proxy2;

                try
                {
                    string tmp;

                    using (var response = (HttpWebResponse)request.GetResponse())
                    {
                        var reader = new StreamReader(response.GetResponseStream());
                        tmp = reader.ReadToEnd();
                    }

                    Console.Write(tmp);

                }
                catch (WebException wex)
                {
                    Console.WriteLine(wex.ToString());

                    var httpResponse = wex.Response as HttpWebResponse;
                    if (httpResponse != null)
                    {
                        if (httpResponse.StatusCode == HttpStatusCode.NotModified)
                        {
                            // resource was not modified.
                        }
                    }

                    // Something else happened. Rethrow or log.
                    //throw;
                }
            }

            Console.WriteLine("exit...");
            Console.ReadLine();
        }
    }
}



//------------------------------------------------------------------------------------

//DisplayRegisteredModules();
//AuthenticationManager.Unregister("Basic");
//AuthenticationManager.Unregister("NTLM");
//AuthenticationManager.Unregister("Negotiate");
//AuthenticationManager.Unregister("Digest");
////AuthenticationManager.Unregister("Kerberos");
//DisplayRegisteredModules();

////Console.WriteLine("User name: " + CredentialCache.DefaultNetworkCredentials.UserName);
////Console.WriteLine("Password: " + CredentialCache.DefaultNetworkCredentials.Password);

//------------------------------------------------------------------------------------







